package red.yancloud.www.ui.activity

import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_red_bag.*
import red.yancloud.www.R
import red.yancloud.www.base.BaseRefreshActivity
import red.yancloud.www.common.Constants
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.RedBag
import red.yancloud.www.internet.bean.TypeData
import red.yancloud.www.ui.adapter.RecycleViewDivider
import red.yancloud.www.ui.adapter.RedBagRecyclerAdapter
import red.yancloud.www.ui.adapter.TypeRecyclerAdapter
import red.yancloud.www.util.AppUtils
import red.yancloud.www.util.ScreenUtils
import red.yancloud.www.util.ToastUtils

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/7/26 19:47
 * E_Mail：yh131412hys@163.com
 * Describe：红书包
 * Change：
 * @Version：V1.0
 */
class RedBagActivity : BaseRefreshActivity(), View.OnClickListener {

    private val TAG = "RedBagActivity"

    private var selectPosition = -1//用于记录用户选择的变量
    private var typeId=""
    private var keyword:String=""

    private lateinit var typeList:ArrayList<TypeData>
    private lateinit var mTypeAdapter : TypeRecyclerAdapter
    private lateinit var mRecyclerAdapter: RedBagRecyclerAdapter

    override val layoutId: Int
        get() = R.layout.activity_red_bag

    override fun configViews() {
        super.configViews()

        back_iv.setOnClickListener(this)
        initSearchEditText()
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.back_iv -> {

                finish()
            }
        }
    }

    private fun initSearchEditText() {

//        在清单文件对应的Activity中添加如下属性，防止布局被软键盘顶上去 android:windowSoftInputMode="stateAlwaysVisible|adjustPan"
        redBagActivity_search_et.setOnEditorActionListener(object : TextView.OnEditorActionListener {

            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {

                if (actionId== EditorInfo.IME_ACTION_SEARCH) {

                    AppUtils.closeInoutDecorView(this@RedBagActivity)
                    keyword = redBagActivity_search_et.text.toString().trim()
                    redBagActivity_search_et.text!!.clear()
                    if (TextUtils.isEmpty(keyword)) {

                        ToastUtils.showToast("请输入搜索关键字")
                        return true
                    }

                    page = 1
                    typeId = ""
                    selectPosition = -1
                    getRefreshDataList()
                    keyword=""
                    return true
                }
                return false
            }
        })
    }

    override fun initRecyclerView() {

        typeList = ArrayList()

        redBagActivity_type_rV.layoutManager= LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL,false)
        mTypeAdapter = TypeRecyclerAdapter(R.layout.item_read_type_list)
        redBagActivity_type_rV.adapter= mTypeAdapter
        mTypeAdapter.onItemClickListener = object : BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                //获取选中的参数
                selectPosition = position
                mTypeAdapter.setSelectPosition(selectPosition)

                //                处理数据不刷新问题
                redBagActivity_type_rV.scrollBy(1,0)
                redBagActivity_type_rV.scrollBy(-1,0)
                page=1
                typeId = typeList[position].typeId
                getRefreshDataList()
            }
        }

        redBagActivity_rV.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        redBagActivity_rV.addItemDecoration(
            RecycleViewDivider(
                this,
                DividerItemDecoration.VERTICAL,
                ScreenUtils.dpToPx(10f).toInt(),
                R.color.color_f5
            )
        )
        mRecyclerAdapter= RedBagRecyclerAdapter()
        redBagActivity_rV.adapter = mRecyclerAdapter
        mRecyclerAdapter.setOnItemClickListener(object :BaseQuickAdapter.OnItemClickListener{
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

                startActivity(
                    Intent(mContext, NewsInfoActivity::class.java)
                        .putExtra(
                            "url",
                            "${Constants.API_BASE_RED_CLOUD_URL}News/index?id=${mRecyclerAdapter.mData[position].id}")
                        .putExtra("model",Constants.CollectModel.REDSBAG)
                        .putExtra("id",mRecyclerAdapter.mData[position].id)
                )
            }
        })
    }

    override fun getRefreshDataList() {

        loadingDialog.show()

        RedCloudApis.getInstance().getRedBagList(page.toString(), limit, typeId, keyword, object : Observer<RedBag> {
            override fun onComplete() {
            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: RedBag) {

                Log.d(TAG,t.toString())
                if (t.code== Constants.SYSTEM_OK) {

                    if(t.data != null){

                        if (t.data.menus != null && t.data.menus.size > 0) {

                            typeList.clear()
                            typeList.add(TypeData("全部",""))
                            for (i in 0 until t.data.menus.size) {

                                typeList.add(TypeData(t.data.menus[i].title, t.data.menus[i].id))
                            }

                            mTypeAdapter.data.clear()
                            mTypeAdapter.setSelectPosition(selectPosition)
                            mTypeAdapter.addData(typeList)
                            if (selectPosition == -1) {

                                redBagActivity_type_rV.scrollToPosition(0)
                            }
                        }

                        if (t.data.page!=null&& t.data.redsbags != null && t.data.redsbags.size > 0){

                            errorView.visibility=View.GONE
                            smartRefreshLayout.visibility=View.VISIBLE

                            totalPage = t.data.page.totalPage
                            if (page==1) {

                                redBagActivity_rV.scrollToPosition(0)
                                mRecyclerAdapter.clear()
                                mRecyclerAdapter.addData(t.data.redsbags)
                                smartRefreshLayout.resetNoMoreData()
                                smartRefreshLayout.finishRefresh()

                                redBagActivity_rV.scrollBy(1,0)
                                redBagActivity_rV.scrollBy(-1,0)
                            }else {

                                mRecyclerAdapter.addData(t.data.redsbags)
                                smartRefreshLayout.finishLoadMore()
                            }
                        }else{

                            errorView.visibility=View.VISIBLE
                            smartRefreshLayout.visibility=View.GONE
                        }
                    }else{

                        if (page==1){

                            smartRefreshLayout.finishRefresh()

                            errorView.visibility=View.VISIBLE
                            smartRefreshLayout.visibility=View.GONE
                        }else{

                            ToastUtils.showToast(getString(R.string.data_all_load))
                            smartRefreshLayout.finishLoadMore()
                        }
                    }
                }else{

                    ToastUtils.showToast(t.msg)
                    errorView.visibility=View.VISIBLE
                    smartRefreshLayout.visibility=View.GONE
                }

                loadingDialog.dismiss()
            }

            override fun onError(e: Throwable) {

                loadingDialog.dismiss()
            }
        })
    }
}
